export default {
    mounted(el, binding) {
        el.style.cursor = 'move';
        el.style.position = 'absolute';  // 使用 absolute 定位，确保元素不会被意外遮挡或跳出屏幕
        el.style.zIndex = 1000; // 确保元素在最前面
      
        const onMouseDown = (e) => {
          let disx, disy;
          if (e.touches) {
            disx = e.touches[0].pageX - el.offsetLeft;
            disy = e.touches[0].pageY - el.offsetTop;
          } else {
            disx = e.pageX - el.offsetLeft;
            disy = e.pageY - el.offsetTop;
          }
      
          const onMouseMove = (e) => {
            let x, y;
            if (e.touches) {
              x = e.touches[0].pageX - disx;
              y = e.touches[0].pageY - disy;
            } else {
              x = e.pageX - disx;
              y = e.pageY - disy;
            }
      
            // 获取页面可视范围的最大值，避免元素超出屏幕
            const maxX = document.documentElement.clientWidth - el.offsetWidth;
            const maxY = document.documentElement.clientHeight - el.offsetHeight;
      
            // 确保元素不会超出页面范围
            if (x < 0) x = 0;
            else if (x > maxX) x = maxX;
      
            if (y < 0) y = 0;
            else if (y > maxY) y = maxY;
      
            // 设置元素的新位置
            el.style.left = x + 'px';
            el.style.top = y + 'px';
          };
      
          const onMouseUp = () => {
            // 移除事件监听，防止内存泄漏
            document.removeEventListener('mousemove', onMouseMove);
            document.removeEventListener('mouseup', onMouseUp);
            document.removeEventListener('touchmove', onMouseMove);
            document.removeEventListener('touchend', onMouseUp);
          };
      
          // 添加事件监听
          document.addEventListener('mousemove', onMouseMove);
          document.addEventListener('mouseup', onMouseUp);
          document.addEventListener('touchmove', onMouseMove);
          document.addEventListener('touchend', onMouseUp);
        };
      
        el.addEventListener('mousedown', onMouseDown);
        el.addEventListener('touchstart', onMouseDown); // 支持触摸设备
      }
    }      